package models

import (
	"github.com/jinzhu/gorm"
	"kop/libs/database"
	"kop/modules/island/entity"
)

func AutoMigrate() {

	database.DB.AutoMigrate(new(entity.Island))
	database.DB.AutoMigrate(new(entity.IslandReport))
	database.DB.AutoMigrate(new(entity.IslandGuildRanking))
}

func GetIslands(islandIDs []int32, serverID int32) []*entity.Island {

	var islands []*entity.Island

	if err := database.DB.Where("island_id IN (?) AND server_id = ? ", islandIDs, serverID).Find(&islands).Error; err != nil {
		panic(err)
	}

	return islands
}

func GetIsland(islandID, serverID int32) *entity.Island {

	var island = &entity.Island{}

	if err := database.DB.Where("island_id = ? AND server_id = ?", islandID, serverID).First(island).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		} else {
			panic(err)
		}
	}

	return island
}

func GetIslandsByRoleID(roleID int32) []entity.Island {

	var islands []entity.Island

	if err := database.DB.Where("role_id = ? ", roleID).Find(&islands).Error; err != nil {
		panic(err)
	}

	return islands
}

func Save(island *entity.Island) error {

	return database.DB.Save(island).Error
}

//func Delete(island *entity.Island) error {
//
//	return database.DB.Delete(island).Error
//}

func Create(island *entity.Island) error {

	return database.DB.Create(island).Error
}
